package com.psp.park.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.northend.util.MD5Util;
import com.northend.util.RandomUtil;
import com.northend.util.qiniu.QiniuManager;
import com.northend.util.qiniu.QiniuReFile;
import com.psp.park.cache.QiniuCache;
import com.psp.park.controller.res.bean.RQiniuFileBean;
import com.psp.park.service.QiniuService;
import com.qiniu.common.Zone;

@Service
public class QiniuServiceImpl implements QiniuService {
	Logger logger = Logger.getLogger(QiniuServiceImpl.class);

	final String accessKey = "MUadFVajknLWbM3LKZWZAdZ9KExWGWWAAW0cEn02";
	final String secretKey = "WLdpuWE3I-93CXeAnEY3wqItfpEdHw2Awg4N2Fcm";
	Zone zone = Zone.zone1();
	final String bucket = "publick";
	final String qiniulinkurl = "http://os4z3g2v6.bkt.clouddn.com/";
	final String qiniuCDNurl = "http://qnimg.zpark-imway.com/";

	QiniuManager qiniuManager = QiniuManager.getInstance(accessKey, secretKey, bucket, zone);

	@Autowired
	QiniuCache qiniuCacheImpl;

	@Override
	public String getQiniuToken(String userId) {
		return getQiniuToken();
	}

	@Override
	public RQiniuFileBean uploadFile(String media_id) {

		// String access_token = wechatServiceImpl.getAccessToken();
		String access_token = "";

		byte[] value = getFileFromWxServer(access_token, media_id);

		logger.info("value size is :" + value.length);

		String qiniuToken = getQiniuToken();
		QiniuReFile file = qiniuManager.upload(qiniuToken,
				MD5Util.md5(System.currentTimeMillis() + RandomUtil.getRandomCharAndNum(10)), value);

		if (file != null) {
			RQiniuFileBean data = new RQiniuFileBean();
			data.setKey(file.getKey());
			data.setImgH(file.getImgH());
			data.setImgW(file.getImgW());
			data.setUrl(qiniuCDNurl + file.getKey());
			return data;
		}

		return null;
	}

	/**
	 * 从微信上获取文件
	 * 
	 * @param access_token
	 * @param media_id
	 * @return
	 */
	private byte[] getFileFromWxServer(String access_token, String media_id) {

		return null;
	}

	/**
	 * 文件的字节数组上传
	 */
	@Override
	public RQiniuFileBean uploadFile(byte[] value) {
		String qiniuToken = getQiniuToken();
		QiniuReFile file = qiniuManager.upload(qiniuToken,
				MD5Util.md5(System.currentTimeMillis() + RandomUtil.getRandomCharAndNum(10)), value);
		if (file != null) {
			RQiniuFileBean data = new RQiniuFileBean();
			data.setKey(file.getKey());
			data.setImgH(file.getImgH());
			data.setImgW(file.getImgW());
			data.setUrl(qiniuCDNurl + file.getKey());
			return data;
		}
		return null;
	}

	/**
	 * 获取七牛 token
	 * 
	 * @return
	 */
	private String getQiniuToken() {
		long expireSeconds = 3600;
		String token = qiniuCacheImpl.getToken();
		if (token == null) {
			token = qiniuManager.getToken(expireSeconds);
			qiniuCacheImpl.setToken(token, expireSeconds - 200);
		}
		return token;
	}
}
